﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using System.Data;
using Newtonsoft.Json;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
      [OutputCache(Duration = 0, VaryByParam = "none")]
    public class LookFtpAuthController : AdminBaseController
    {
        //
        // GET: /Admin/LookFtpAuth/
        [AuthorityActionFilter("m_LookFtpAuth", Order = 1)]
        [LogPageActionFilter("部门查看权限", Order = 2)]
        public ActionResult Index()
        {
            ViewData["tableJsonStr"] = GetTableJsonStr();
            string strTable = ViewData["tableJsonStr"].ToString();

            ViewData["strTable"] = GetEmpTable(strTable);
            return View();
        }
        private BLL.HRDept hrDeptBLL = new BLL.HRDept();
        private BLL.HREmpl hrEmplBLL = new BLL.HREmpl();
        public ActionResult AttndanceDefinedChooseTree()
        {
            string entityNo = GlobalConstant.ENTITYNO;
            BLL.AttendanceDefined attendanceDefinedBLL = new BLL.AttendanceDefined();
            DataTable emplDT = attendanceDefinedBLL.GetAllListWithOutIsMainPosition(entityNo);
            List<Model.HRDept> HRDeptList = new List<Model.HRDept>();
            HRDeptList = hrDeptBLL.GetListByEntityNo(entityNo);
            return BindDeptTreeData("AttndanceDefinedChooseTree", null, emplDT, "3", true, HRDeptList);
        }
        public string UpdateGetTableJsonStr(string returnValue = "")
        {
            try
            {
                string entityNo = GlobalConstant.ENTITYNO;
                List<SelectListItem> itemList = JsonConvert.DeserializeObject<List<SelectListItem>>(returnValue);
                List<Model.HREmpl> emplModelList = new List<Model.HREmpl>();

                foreach (SelectListItem selectItem in itemList)
                {
                    Model.HREmpl emplModel = new Model.HREmpl();
                    emplModel.FEmplNo = selectItem.Value;
                    emplModel.FEmpName = selectItem.Text;
                    emplModel.FEntityNo = entityNo;
                    emplModel.FIsAllowLookFtp = "Y";
                    emplModelList.Add(emplModel);

                }
                hrEmplBLL.UpdataEmplFIsAllowLookFtp(emplModelList,entityNo);
                return "ok";
            }
            catch (System.Exception ex)
            {
                return "更新员工表失败错误代码:" + ex.Message.ToString();
            }

        }
        public string GetTableJsonStr()
        {
             string entityNo = GlobalConstant.ENTITYNO;
             string tableJsonStr = "";
            if (hrEmplBLL.GetEmplListFIsAllowLookFtp(entityNo).Count>0)
            {
                
            

            tableJsonStr += "[";

            foreach (Model.HREmpl emp in hrEmplBLL.GetEmplListFIsAllowLookFtp(entityNo))
            {
                tableJsonStr += hrEmplBLL.GetEmpNameAndDeptFIsAllowLookFtp(entityNo, emp.FEmplNo) + ",";
            }
            tableJsonStr = tableJsonStr.Substring(0, tableJsonStr.LastIndexOf(","));
            tableJsonStr += "]";
            } 
            else
            {

            }
           
           ;
            return tableJsonStr;
        }
        private ActionResult BindDeptTreeData(string viewName, List<Model.HRPosition> hrPositionList = null, DataTable emplDT = null, string selectMode = "3", bool checkboxMode = true, List<Model.HRDept> hrDeptList = null)
        {
            string entityNo = GlobalConstant.ENTITYNO;
            string treeJsonStr = "";
            treeJsonStr += "[";
            if (hrDeptList == null)
            {
                hrDeptList = hrDeptBLL.GetListByEntityNo(entityNo);
            }
            if (hrDeptList.Count > 0)
            {
                Dictionary<int, List<Model.HRDept>> dicHRDeptList = new Dictionary<int, List<Model.HRDept>>();
                if (GlobalConstant.ENTITYNO == "05")
                {
                    //鄞州财政
                    //局机关
                    dicHRDeptList.Add(0, hrDeptList.Where(s => s.FIsAgency == "N").OrderBy(s => s.FDeptNo).ToList());
                    //派出机构(镇乡街道)
                    dicHRDeptList.Add(1, hrDeptList.Where(s => s.FIsAgency == "Y").OrderBy(s => s.FDeptNo).ToList());

                }
                else
                {
                    dicHRDeptList.Add(0, hrDeptList);
                }
                foreach (KeyValuePair<int, List<Model.HRDept>> dicDept in dicHRDeptList)
                {
                    if (dicHRDeptList.Count == 1)
                    {
                        treeJsonStr += "{'title':'组织结构','key':'-1','expand':true,'isFolder':true,'activate':true";
                        treeJsonStr += ",'children':[";
                    }
                    else
                    {

                        if (dicDept.Key == 0)
                        {
                            treeJsonStr += "{'title':'局机关','key':'-1','expand':true,'isFolder':true,'activate':true";
                            treeJsonStr += ",'children':[";

                        }
                        else
                        {
                            if (dicDept.Value.Count > 0)
                            {
                                treeJsonStr += "{'title':'镇乡街道','key':'-1','expand':true,'isFolder':true,'activate':true";
                                treeJsonStr += ",'children':[";
                            }
                        }
                    }
                    List<Model.HRDept> keyHRDeptList = dicDept.Value;
                    foreach (Model.HRDept hrDeptModel in keyHRDeptList)
                    {
                        List<Model.HRDept> tmpChildDeptList = keyHRDeptList.Where(s => s.FParentDeptNo == hrDeptModel.FDeptNo).ToList();
                        int childCount = tmpChildDeptList.Count;
                        if (childCount > 0)
                        {
                            treeJsonStr += "{'title':'" + hrDeptModel.FDeptName + "','key':'" + hrDeptModel.FDeptNo + "','expand':false,'isFolder':true,'activate':true,'icon':'" + Url.Content("~/Content/ControlImages/dept_Groups.png") + "'";
                            treeJsonStr += ",'children':[";
                            GetChildHRDept(tmpChildDeptList, ref treeJsonStr, keyHRDeptList, hrPositionList, emplDT);
                            //绑定部门
                            if (hrPositionList != null)
                            {
                                List<Model.HRPosition> tmpPositionList = hrPositionList.Where(c => c.FDeptNo == hrDeptModel.FDeptNo).ToList();
                                if (tmpPositionList.Count > 0)
                                {
                                    treeJsonStr += ",";
                                    GetPostion(tmpPositionList, ref treeJsonStr);

                                }
                            }
                            //绑定人员
                            if (emplDT != null)
                            {
                                var tmpEmp = (from c in emplDT.AsEnumerable()
                                              where c["FDeptNo"].ToString() == hrDeptModel.FDeptNo
                                              select c);
                                if (tmpEmp.Count() > 0)
                                {
                                    DataTable tmpEmplDT = tmpEmp.CopyToDataTable();
                                    treeJsonStr += ",";
                                    GetEmpl(tmpEmplDT, ref treeJsonStr);
                                }

                            }
                            treeJsonStr += "]";

                        }
                        else
                        {
                            treeJsonStr += "{'title':'" + hrDeptModel.FDeptName + "','key':'" + hrDeptModel.FDeptNo + "','expand':false,'isFolder':false,'activate':true,'icon':'" + Url.Content("~/Content/ControlImages/dept_Groups.png") + "'";
                            //绑定部门
                            if (hrPositionList != null)
                            {
                                List<Model.HRPosition> tmpPositionList = hrPositionList.Where(c => c.FDeptNo == hrDeptModel.FDeptNo).ToList();
                                if (tmpPositionList.Count > 0)
                                {
                                    treeJsonStr += ",'children':[";
                                    GetPostion(tmpPositionList, ref treeJsonStr);
                                    treeJsonStr += "]";
                                }
                            }
                            //绑定人员
                            if (emplDT != null)
                            {
                                var tmpEmp = (from c in emplDT.AsEnumerable()
                                              where c["FDeptNo"].ToString() == hrDeptModel.FDeptNo
                                              select c);
                                if (tmpEmp.Count() > 0)
                                {
                                    DataTable tmpEmplDT = tmpEmp.CopyToDataTable();
                                    treeJsonStr += ",'children':[";
                                    GetEmpl(tmpEmplDT, ref treeJsonStr);
                                    treeJsonStr += "]";
                                }
                            }

                        }
                        treeJsonStr += "},";
                    }
                    if (keyHRDeptList.Count > 0)
                    {
                        treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
                        treeJsonStr += "]";
                        treeJsonStr += "},";
                    }
                }
                treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
                treeJsonStr += "]";

            }
            else
            {
                //treeJsonStr += "{'title':'组织结构','key':'-1','expand':true,'isFolder':false,'activate':true";
                treeJsonStr += "]";
            }

            //treeJsonStr += "},";
            //treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
            //treeJsonStr += "]";
            treeJsonStr = treeJsonStr.Replace("\\", "");
            treeJsonStr = treeJsonStr.Replace("'", "\"");
            ViewData["treeJsonStr"] = treeJsonStr;
            ViewData["treeSelectMode"] = selectMode;
            ViewData["checkboxMode"] = checkboxMode.ToString().ToLower();
            return View(viewName);
        }

        /// <summary>
        /// 递归获取子部门
        /// </summary>
        /// <param name="hrDeptChildList">子部门列表</param>
        /// <param name="treeJsonStr">json树的字符串</param>
        /// <param name="hrDeptList">全部部门列表</param>
        /// <param name="emplDT">全部人员DT</param>
        private void GetChildHRDept(List<Model.HRDept> hrDeptChildList, ref string treeJsonStr, List<Model.HRDept> hrDeptList, List<Model.HRPosition> hrPositionList, DataTable emplDT)
        {
            foreach (Model.HRDept tmpDeptModel in hrDeptChildList)
            {
                List<Model.HRDept> tmpChildDeptList = hrDeptList.Where(s => s.FParentDeptNo == tmpDeptModel.FDeptNo).ToList();

                int childCount = tmpChildDeptList.Count;
                if (childCount > 0)
                {
                    treeJsonStr += "{'title':'" + tmpDeptModel.FDeptName + "','key':'" + tmpDeptModel.FDeptNo + "','expand':false,'isFolder':true,'activate':true";
                    treeJsonStr += ",'children':[";
                    GetChildHRDept(tmpChildDeptList, ref treeJsonStr, hrDeptList, hrPositionList, emplDT);
                    //绑定部门
                    if (hrPositionList != null)
                    {
                        List<Model.HRPosition> tmpPositionList = hrPositionList.Where(c => c.FDeptNo == tmpDeptModel.FDeptNo).ToList();
                        if (tmpPositionList.Count > 0)
                        {
                            treeJsonStr += ",";
                            GetPostion(tmpPositionList, ref treeJsonStr);

                        }
                    }
                    //绑定人员
                    if (emplDT != null)
                    {
                        var tmpEmp = (from c in emplDT.AsEnumerable()
                                      where c["FDeptNo"].ToString() == tmpDeptModel.FDeptNo
                                      select c);
                        if (tmpEmp.Count() > 0)
                        {
                            DataTable tmpEmplDT = tmpEmp.CopyToDataTable();
                            treeJsonStr += ",";
                            GetEmpl(tmpEmplDT, ref treeJsonStr);
                        }

                    }
                    treeJsonStr += "]";

                }
                else
                {
                    treeJsonStr += "{'title':'" + tmpDeptModel.FDeptName + "','key':'" + tmpDeptModel.FDeptNo + "','expand':false,'isFolder':false,'activate':true,'icon':'" + Url.Content("~/Content/ControlImages/dept_Groups.png") + "'";
                    //绑定部门
                    if (hrPositionList != null)
                    {
                        List<Model.HRPosition> tmpPositionList = hrPositionList.Where(c => c.FDeptNo == tmpDeptModel.FDeptNo).ToList();
                        if (tmpPositionList.Count > 0)
                        {
                            treeJsonStr += ",'children':[";
                            GetPostion(tmpPositionList, ref treeJsonStr);
                            treeJsonStr += "]";
                        }
                    }
                    //绑定人员
                    if (emplDT != null)
                    {
                        var tmpEmp = (from c in emplDT.AsEnumerable()
                                      where c["FDeptNo"].ToString() == tmpDeptModel.FDeptNo
                                      select c);
                        if (tmpEmp.Count() > 0)
                        {
                            DataTable tmpEmplDT = tmpEmp.CopyToDataTable();
                            treeJsonStr += ",'children':[";
                            GetEmpl(tmpEmplDT, ref treeJsonStr);
                            treeJsonStr += "]";
                        }
                    }

                }
                treeJsonStr += "},";
            }
            treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
        }

        /// <summary>
        /// 绑定岗位树岗位数据
        /// </summary>
        /// <param name="hrPositionDeptList">该部门岗位列表</param>
        /// <param name="treeJsonStr">json树的字符串</param>
        private void GetPostion(List<Model.HRPosition> hrPositionDeptList, ref string treeJsonStr)
        {
            foreach (Model.HRPosition hrPositionModel in hrPositionDeptList)
            {
                treeJsonStr += "{'title':'" + hrPositionModel.FPositionName + "','key':'" + hrPositionModel.FPositionNo + "','expand':false,'isFolder':false,'activate':true,'icon':'" + Url.Content("~/Content/ControlImages/mail_post_to.png") + "','addClass':'position'";
                treeJsonStr += "},";
            }
            treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
        }
        /// <summary>
        /// 绑定人员树数据
        /// </summary>
        /// <param name="emplDeptDT">该部门人员DT</param>
        /// <param name="treeJsonStr">json树的字符串</param>
        private void GetEmpl(DataTable emplDeptDT, ref string treeJsonStr)
        {
            foreach (DataRow dr in emplDeptDT.Rows)
            {
                treeJsonStr += "{'title':'" + dr["FEmpName"].ToString() + "','key':'" + dr["FEmplNo"].ToString() + "','expand':false,'isFolder':false,'activate':true,'icon':'" + Url.Content("~/Content/ControlImages/user_male.png") + "','addClass':'user'";
                treeJsonStr += "},";
            }
            treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
        }
        public string GetEmpTable(string strTable)
        {
            if (string.IsNullOrEmpty(strTable))
            {
                return "";
            }
            string str = "";
            string deptNo = "";
            int td = 8;//一行显示的人员个数
            int ss = 0;//每个部门的总人数
            int tr = 0;
            List<Model.HREmpl> itemList = JsonConvert.DeserializeObject<List<Model.HREmpl>>(strTable).ToList().OrderBy(h=>h.FDeptNo).ToList();
            List<int> intList = new List<int>();

            for (int i = 0; i < itemList.Count; i++)
            {
                if (deptNo != itemList[i].FDeptNo)
                {
                    deptNo = itemList[i].FDeptNo;
                    if (ss != 0)
                    {
                        intList.Add(ss);
                    }
                    ss = 0;
                    ss++;
                    tr++;
                }
                else
                {
                    ss++;
                }
            }
            intList.Add(ss);

            List<int> trIntList = new List<int>();

            foreach (int p in intList)
            {
                int a = 0;
                a = p;
                if (a % td == 0)
                {
                    a = a / td;
                }
                else
                {
                    a = a / td + 1;
                }
                trIntList.Add(a);
            }


            deptNo = "";
            str += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"99%\" class=\"table\">";
            str += "<tr><td style=\"font-size:14px;font-weight:bold;text-align:center;width:100px;\">部门</td><td style=\"font-size:14px;font-weight:bold;text-align:center\" colspan=\"" + td + "\">人员</td></tr>";
            int j = 0;
            int sum = 0;
            int count = 0;
            foreach (Model.HREmpl model in itemList)
            {
                if (deptNo != model.FDeptNo)
                {
                    deptNo = model.FDeptNo;

                    if (j > 0)
                    {
                        if (sum < td)
                        {
                            for (int i = 0; i < td - sum; i++)
                            {
                                str += "<td>&nbsp;</td>";
                            }
                        }
                        str += "</tr>";
                    }

                    str += "<tr>";
                    str += "<td style=\"font-size:12px;font-weight:bold;text-align:center;\" rowspan=\"" + trIntList[j] + "\">" + model.FDeptName + "</td>";
                    str += "<td style=\"text-align:center;\" width=\"40\">" + model.FEmpName + "</td>";

                    j++;
                    sum = 0;
                    sum++;
                }
                else
                {
                    if (sum >= td)
                    {
                        str += "</tr><tr><td style=\"text-align:center;\" width=\"40\">" + model.FEmpName + "</td>";
                        //int abs = Math.Abs(sum - td - td) + 1;
                        //for (int i = 0; i < abs; i++)
                        //{
                        //    str += "<td class=\"tdClass\" width=\"50\">&nbsp;</td>";
                        //}
                        sum = 0;
                        count++;
                    }
                    else
                    {
                        str += "<td style=\"text-align:center;\" width=\"40\">" + model.FEmpName + "</td>";
                    }
                    sum++;
                }
            }
            //str += "</tr>";
            //int abs1 = Math.Abs(sum - td) + 2;
            //for (int i = 0; i < abs1; i++)
            //{
            //    str += "<td class=\"tdClass\" width=\"50\">&nbsp;</td>";
            //}
            //if (ss > 0)
            //{
            //    str += "</tr>";
            //}
            if (sum < td)
            {
                for (int i = 0; i < td - sum; i++)
                {
                    str += "<td>&nbsp;</td>";
                }
            }
            str += "</tr>";
            str += "</table>";
            return str;
        }


    }
}
